package com.example.nio.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.example.nio.commons.*;
import com.example.nio.dao.StatisReportMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

/**
 *
 * @author yongjiehuang
 * @date 2019年1月27日
 */
@Component
@Slf4j
public class FlowNumHandler {

	@Autowired
	private MongoTemplate mongoTemplate;
	/**
	 * 存信息，流水号存在则插入新的记录，无则新增
	 *
	 * @param flowNum
	 * @param message
	 */
	public void put(String flowNum, ChatMessage message) {
		log.info("**************"+flowNum);
		try {
			mongoTemplate.insert(Convert.convert(MMessage.class, message));
		}catch (Exception e){
			System.out.println("mongodb添加数据失败");
		}
	}



	/**
	 * 根据流水号获得记录
	 *
	 * @param flowNum
	 * @return
	 */

	public String get(String flowNum) {
		List<MMessage> messageList = mongoTemplate.find(new Query(new Criteria().orOperator(Criteria.where("from").is(flowNum),Criteria.where("to").is(flowNum))), MMessage.class);
		return JSONUtil.toJsonStr(messageList.stream().map(mm->(MMessage)mm).collect(Collectors.toList()));
	}


	public Page<MMessage> getChatList(int currentPage, int pageSize, String username, String content,String timeStart,String timeEnd){
		// mongoDb or查询
		Criteria criteria = new Criteria().orOperator(Criteria.where("fromUser").is(username),Criteria.where("toUser").is(username));
		if (timeStart != null && !"".equals(timeStart) && timeEnd != null && !"".equals(timeEnd)){
//			StatisReport statisReport = statisReportMapper.getOneByStatisticsId(statisticsId);
//			statisReport.getCallStart();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			try {
				criteria.andOperator(Criteria.where("systemTime").lt(simpleDateFormat.parse(timeEnd).getTime()).gte(simpleDateFormat.parse(timeStart).getTime()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		Query skip = new Query().addCriteria(criteria);
		if (content != null && !"".equals(content)){
			skip = skip.addCriteria(Criteria.where("content").regex(".*?" + content + ".*"));
//					.with(Sort.by(Sort.Direction.ASC,"systemTime"))
//					.limit(pageSize).skip((currentPage-1) * pageSize);
		}
		long total = mongoTemplate.count(skip,MMessage.class);
		if(total == 0) {
			return Page.empty();
		}
		PageRequest pageable = PageRequest.of(currentPage-1, pageSize, Sort.Direction.DESC, "systemTime");
		skip.with(pageable);
		List<MMessage> messageList = mongoTemplate.find(skip, MMessage.class);
		return new PageImpl<>(messageList,pageable,total);
	}


	/**
	 * 等待队列存储
	 */
	public void putListWait(String flowNum, User user, Agent agent) {
		Message message=new Message();
		message.setDepartment(agent.getDepartment());
		message.setFrom(user.getOpenId());
		message.setHeadimgurl(user.getHeadimgurl());
		message.setNickname(user.getNickname());
		message.setShowdate(new Date());
		message.setTo(agent.getAgent());
		message.setServerType(1);
	}
}
